package com.buba.springcloud.aspect;
import com.buba.springcloud.annotation.RecordOperation;
import com.buba.springcloud.entities.HfUser;
import com.buba.springcloud.util.JwtUtil;
import com.buba.springcloud.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
public class RecordOperationAspect {

    private final RedisUtil redisUtil;


    public RecordOperationAspect(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Pointcut("@annotation(com.buba.springcloud.annotation.RecordOperation)")
    public void advice() {
    }


    @Before("advice()")
    public void doBefore(JoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法
        Method method = signature.getMethod();
        RecordOperation annotation = method.getAnnotation(RecordOperation.class);
        assert annotation != null;

        if (annotation.flag()) {
            log.info("-------------------------记录操作-----------------------");

            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            //获取token
            String token = request.getHeader("token");
            String id = null;
            try {
                id = JwtUtil.parseJWT(token).get("id").toString();
            } catch (Exception e) {
                log.info("token已过期");
            }
            HfUser userInfo = (HfUser) redisUtil.get("fuser"+id);
            if (Objects.isNull(userInfo)) {
                //你们过期操作

            } else {
                log.info("--------------------开始重置时间--------------------");
                boolean expire = redisUtil.expire(id, 30, TimeUnit.MINUTES);
                String jwt = JwtUtil.createJWT(1000*60*30, userInfo);
                if (jwt!=null){
                    log.info("token重置成功");
                }else {
                    log.info("token重置失败");
                }
                if (expire) {
                    log.info("----------------------重置成功----------------------");
                } else {
                    log.info("----------------------重置失败----------------------");
                }
            }
        }

    }
}
